import { useContext, useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useMediaPredicate } from 'react-media-hook';
import { useDispatch, useSelector } from 'react-redux';
import { RootState } from 'src/redux/store'
import { useNavigate } from 'react-router-dom';
import BackButton from 'src/component/BackButton';
import Pagination from 'src/component/Pagination';
import DateFilter from 'src/component/RoundDateFilter';
import Select from 'src/component/Select';
import SelectOption from 'src/component/SelectOption';
import Switcher from 'src/component/Switcher';
import { MediaQuery } from 'src/constant/Media';
import { Page } from 'src/constant/Page';
import { ThemeContext } from 'src/context/ThemeContext';
import { useDateFilter } from 'src/hook/useDateFilter';
import { usePagination } from 'src/hook/usePagination';
import useQuery from 'src/hook/useQuery';
// import { DepositRecord } from 'src/model/Deposit';
// import { WithdrawalRecord } from 'src/model/Withdrawal';
import { openSnackbar } from 'src/redux/uiSlice';
// import { cancelWithdrawal, getRecordData } from 'src/service/propertyService';
import { getMyWithdraw, getMyRecharge } from 'src/service/moneyService';
import CancelModal from './component/CancelModal';
import DepositCard from './component/DepositCard';
import DepositTable from './component/DepositTable';
import VerifyModal from './component/VerifyModal';
import WithdrawalCard from './component/WithdrawalCard';
import WithdrawalTable from './component/WithdrawalTable';
import style from './Record.module.scss';


type DepositRecord = any
type WithdrawalRecord = any

const Record = () => {
  const { t } = useTranslation();
  const dispatch = useDispatch();
  const { offset, limit, setCount, paginationProps } = usePagination();
  const { begin, end, dateFilterProps } = useDateFilter();
  const { IcEmpty } = useContext(ThemeContext).image;
  const navigate = useNavigate();
  const { type: queryType } = useQuery<{ type: string }>();
  const isBiggerThanMd = useMediaPredicate(MediaQuery.Md);
  const [coinType, setCoinType] = useState<string>('USDT');
  const [refresh, setRefresh] = useState<boolean>(false);
  const [cancelId, setCancelId] = useState<string>();
  const [verifyWithdrawalData, setVerifyWithdrawalData] = useState<WithdrawalRecord>();
  const [transactionType, setTransactionType] = useState<'充值' | 'withdrawal'>(
    queryType === '充值' || queryType === 'withdrawal' ? queryType : '充值',
  );
  const [depositRecordArray, setDepositRecordArray] = useState<Array<DepositRecord>>([]);
  const [alldepositRecordArray, setAllDepositRecordArray] = useState<Array<DepositRecord>>([]);
  const [withdrawalRecordArray, setWithdrawalRecordArray] = useState<Array<WithdrawalRecord>>([]);
  const [allwithdrawalRecordArray, setAllWithdrawalRecordArray] = useState<Array<WithdrawalRecord>>([]);
  const token = localStorage.getItem("token")
  const { accountInfo } = useSelector((rootState: RootState) => rootState.auth);
  useEffect(() => {
    if (!accountInfo?.FID) return

    let obj = {
      FUserID: accountInfo?.FID,
      FType: coinType,
      Sdate: begin,
      Edate: end,
      token: token
    }
    // 充值
    getMyRecharge(obj).then(res => {
      if (res.success) {
        setAllDepositRecordArray(res.list)
        setCount(res.list.length)
      } else {
        dispatch(openSnackbar({ message: res.message, severity: 'alert' }))
      }
    })
    // 提现
    getMyWithdraw(obj).then(res => {
      if (res.success) {
        setAllWithdrawalRecordArray(res.list)
        setCount(res.list.length)
      } else {
        dispatch(openSnackbar({ message: res.message, severity: 'alert' }))
      }
    })

  }, [coinType, transactionType, begin, end, limit, refresh, accountInfo]);

  // 充值
  useEffect(() => {
    if (alldepositRecordArray.length < 1) return
    let len = offset + limit
    let data = alldepositRecordArray.slice(offset, len)
    setDepositRecordArray(data);
  }, [offset, limit, alldepositRecordArray])
  // 提现
  useEffect(() => {
    if (allwithdrawalRecordArray.length < 1) return
    let len = offset + limit
    let data = allwithdrawalRecordArray.slice(offset, len)
    setWithdrawalRecordArray(data);
  }, [offset, limit, allwithdrawalRecordArray])

  const navigateCallback = (record: DepositRecord | WithdrawalRecord) => {
    if (transactionType === '充值') navigate(`${Page.Deposit}/${record.id}`);
    else navigate(`${Page.Withdrawal}/${record.id}`, {
      state: {
        ...record,
      },
    });
  };

  const onCancelWithdrawal = (id: string) => {
    setCancelId(id);
  };

  const onCancelConfirm = () => {
    if (!cancelId) return;
    setCancelId(undefined);
    // cancelWithdrawal(cancelId)
    //   .then(() => setRefresh(!refresh))
    //   .catch((e) => dispatch(openSnackbar({ message: e, severity: 'alert' })));
  };

  const onVerifyClick = (data: WithdrawalRecord) => {
    setVerifyWithdrawalData(data);
  };

  return (
    <div>
      <BackButton />
      <div className={style.heading}>充值与提领纪录</div>
      <div className={style.tabBlock}>
        <Switcher
          labels={["充值", "提现"]}
          defaultIndex={transactionType === '充值' ? 0 : 1}
          onChange={(index) => {
            setTransactionType(index === 0 ? '充值' : 'withdrawal');
            paginationProps.setPage(1);
          }}
        />
      </div>
      <div className={style.recordBlock}>
        <div className={style.filterBlock}>
          <DateFilter onChange={() => paginationProps.setPage(1)} {...dateFilterProps} />
          <div className={style.coinFilter}>
            币别
            <div className={style.selector}>
              <Select
                defaultValue="USDT"
                onChange={(v) => {
                  setCoinType(v);
                  paginationProps.setPage(1);
                }}
              >
                <SelectOption value="USDT">USDT</SelectOption>
              </Select>
            </div>
          </div>
        </div>
        <div className={style.divider} />
        {((transactionType === '充值' && depositRecordArray.length === 0) ||
          (transactionType === 'withdrawal' && withdrawalRecordArray.length === 0)) && (
            <div className={style.emptyImg}>
              <img src={IcEmpty} />
            </div>
          )}
        {transactionType === '充值' &&
          depositRecordArray.length > 0 &&
          (isBiggerThanMd ? (
            <DepositTable data={depositRecordArray} navigateCallback={navigateCallback} />
          ) : (
            <DepositCard data={depositRecordArray} navigateCallback={navigateCallback} />
          ))}
        {transactionType === 'withdrawal' &&
          withdrawalRecordArray.length > 0 &&
          (isBiggerThanMd ? (
            <WithdrawalTable
              data={withdrawalRecordArray}
              navigateCallback={navigateCallback}
              onCancel={onCancelWithdrawal}
              onVerifyClick={onVerifyClick}
            />
          ) : (
            <WithdrawalCard
              data={withdrawalRecordArray}
              navigateCallback={navigateCallback}
              onCancel={onCancelWithdrawal}
              onVerifyClick={onVerifyClick}
            />
          ))}
      </div>
      <div className={style.pagination}>
        <Pagination {...paginationProps} />
      </div>
      <CancelModal
        open={!!cancelId}
        onClose={() => setCancelId(undefined)}
        onSubmit={onCancelConfirm}
      />
      <VerifyModal
        open={!!verifyWithdrawalData}
        onClose={() => setVerifyWithdrawalData(undefined)}
        withdrawalData={verifyWithdrawalData}
        refresh={() => setRefresh(!refresh)}
      />
    </div>
  );
};

export default Record;
